package com.yyc.stocktake2.ui.frg

import android.os.Bundle
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.kingja.loadsir.core.LoadService
import com.yyc.stocktake2.R
import com.yyc.stocktake2.base.BaseFragment
import com.yyc.stocktake2.bean.AppRoomDataBase
import com.yyc.stocktake2.bean.db.AssetBean
import com.yyc.stocktake2.databinding.FDownloadBinding
import com.yyc.stocktake2.ext.initClose
import com.yyc.stocktake2.ext.loadServiceInit
import com.yyc.stocktake2.ext.showEmpty
import com.yyc.stocktake2.ext.showLoading
import com.yyc.stocktake2.mar.eventViewModel
import com.yyc.stocktake2.util.CacheUtil
import com.yyc.stocktake2.viewmodel.DownloadModel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.BehaviorSubject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

import me.hgj.jetpackmvvm.ext.nav
import java.text.NumberFormat
import java.util.concurrent.TimeUnit


/**
 * @Author nike
 * @Date 2023/7/7 16:51
 * @Description  警报日记
 */
class DownloadFrg : BaseFragment<DownloadModel, FDownloadBinding>() {

    //界面状态管理者
    lateinit var loadsir: LoadService<Any>

    val numberFormat = NumberFormat.getInstance()

    // 创建一个 BehaviorSubject 来存储和发出数据列表
    lateinit var dataSubject: BehaviorSubject<List<AssetBean>>

    // 创建一个 CompositeDisposable 来管理所有的 Disposable
    var compositeDisposable: CompositeDisposable? = null

    override fun initView(savedInstanceState: Bundle?) {
        setHasOptionsMenu(true)
        mDatabind.viewmodel = mViewModel
        mDatabind.includeToolbar.toolbar.initClose(getString(R.string.download)) {
            nav().navigateUp()
        }
        //状态页配置
        loadsir = loadServiceInit(mDatabind.layout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.onRequest()
        }

        numberFormat.setMaximumFractionDigits(2)

//        mDatabind.progressView.setOnProgressChangeListener{
//            mDatabind.progressView.labelText = "Download ${it.toInt()}%"
//        }
        mDatabind.circularProgressBar.onProgressChangeListener = { progress ->
            mViewModel.progressText.set("${progress.toInt()}%")
        }

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                compositeDisposable?.dispose()
                mActivity.setSupportActionBar(null)
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.listBean.observe(viewLifecycleOwner, Observer {
            if (it.isSuccess) {
                eventViewModel.mainListEvent.postValue(true)
                if (it.pageSize != 0) {
                    dataSubject = BehaviorSubject.create()
                    compositeDisposable = CompositeDisposable()
                    mViewModel.assetDao.findAll(mViewModel.roNo!!, mViewModel.companyID!!)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({ list ->
                            dataSubject?.onNext(list)
                        }, { throwable ->
                            LogUtils.e("MainActivity", "Error fetching data", throwable)
                        })
                        .let { compositeDisposable?.add(it) }
                    // 每隔2秒从 BehaviorSubject 获取数据并打印列表的大小
                    Observable.interval(1, TimeUnit.SECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({ long ->
                            dataSubject?.value?.let { list ->
                                var number = list.size
                                var result = numberFormat.format(number.toFloat() / it.pageSize.toFloat() * 100).toFloat()
                                mDatabind.circularProgressBar.progress = result
                                runOnUiThread {
                                    mDatabind.circularProgressBar.setProgressWithAnimation(result, 1000)
                                }
                                LogUtils.i(number, result)
                                if (number >= it.pageSize) {
                                    compositeDisposable?.dispose()
                                }
                            }
                        }, { throwable ->
                            // 添加 onError 回调
                            LogUtils.e("MainActivity", "Error in interval observable", throwable)
                        })
                        .let { compositeDisposable?.add(it) }
                }
            } else {
                loadsir.showEmpty()
            }
        })
    }

    override fun lazyLoadData() {
        //设置界面 加载中
        mViewModel.onRequest()
    }


}